package ro.upt.dcda.web;

import java.io.InputStream;
import java.net.InetAddress;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;

public class LocationReader {

	private static DatabaseReader reader;

	public static synchronized CityResponse getLocation(InetAddress ip) {
		if (reader == null) {
			try {
				InputStream database = DatabaseReader.class.getClassLoader()
						.getResourceAsStream("GeoLite2-City.mmdb");
				reader = new DatabaseReader.Builder(database).build();
			} catch (Exception ex) {
				ex.printStackTrace(System.out);
			}
		}
		try {
			return reader.city(ip);
		} catch (Exception ex) {
			return null;
		}
	}

	public static String locationToString(CityResponse city) {
		// System.out.println(response.getCountry().getIsoCode()); // 'US'
		// System.out.println(response.getCountry().getName()); // 'United
		// States'
		// System.out.println(response.getCountry().getNames().get("zh-CN")); //
		// '美国'
		//
		// System.out.println(response.getMostSpecificSubdivision().getName());
		// // 'Minnesota'
		// System.out.println(response.getMostSpecificSubdivision().getIsoCode());
		// // 'MN'
		//
		// System.out.println(response.getCity().getName()); // 'Minneapolis'
		//
		// System.out.println(response.getPostal().getCode()); // '55455'
		//
		// System.out.println(response.getLocation().getLatitude()); // 44.9733
		// System.out.println(response.getLocation().getLongitude()); //
		// -93.2323
		if (city == null) {
			return "Unknown";
		}
		return city.getCity().getName() + " ("
				+ city.getLocation().getLatitude() + ","
				+ city.getLocation().getLongitude() + ")";
	}
}
